package cn.ymatrix.WeChat.groupMessage;

import java.io.IOException;
import java.util.*;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.google.gson.Gson;

// 企业微信API调用请查看: https://developer.work.weixin.qq.com/document/path/91770
public class WeChatSendGroupMsg {

    public static void main(String[] args) {
        try {
            // 获取YMatrix的数据
            Map<Object, Object> msp = DBAlarmDataUrils.dbAarmResultSet();
            String alarm_time = msp.get("alarm_time").toString();
            int alarm_count = Integer.parseInt(msp.get("alarm_count").toString());
            if (alarm_count >= 10) {
                // 发送消息
                WeChatSendGroupMsg.sendMsg("userID,@all", "alarm_time:" + alarm_time + "\n alarm_count:" + alarm_count);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    private static CloseableHttpClient httpClient;

    private static HttpPost httpPost; //用于提交登录数据

    private static String sendmessage_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f5c37026-980f-4843-ab3e-b5bc2b64141e"; //微信消息发送请求地址

    private static String content_type = "Content-Type"; //消息体内容类型

    private static String text_msg_type = "text"; //消息类型（文本/图片等）

    private static String markdown_msg_type = "markdown"; //markdown 格式的数据

    private static String char_set = "utf-8"; //消息编码

    private static Gson gson = new Gson();


    /**
     * @param toUser:  需要发送的用户,需要使用逗号隔开,例如zhangsan,lisi,@all 代表所有人员
     * @param content: 需要发送的消息内容
     * @throws IOException
     * @Title 创建微信发送请求httpPost，并执行
     */
    public static void sendMsg(String toUser, String content) {
        String postData = formatTextData(toUser, content);
        System.out.println("postData:" + postData);
        httpClient = HttpClients.createDefault();
        try {
            httpPost = new HttpPost(sendmessage_url);
            httpPost.setHeader(content_type, content_type);
            httpPost.setEntity(new StringEntity(postData, char_set));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 格式化微信发送请求post数据
     * 本方法适用于text型微信消息
     *
     * @param touser  接收人账号
     * @param content 消息内容
     * @return
     */
    public static String formatTextData(String touser, String content) {
        String[] s = touser.split(",");
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < s.length; i++) {
            arrayList.add(s[i]);
        }
        Map<Object, Object> contents = new HashMap<Object, Object>();
        contents.put("content", content);
        contents.put("mentioned_list", arrayList);
        WeChatSendDataFormat wcd = new WeChatSendDataFormat(touser, markdown_msg_type, "", contents);
        return gson.toJson(wcd);
    }

    /**
     * 微信消息实体类
     */
    public static class WeChatSendDataFormat {

        @SuppressWarnings("unused")
        private String touser; //通讯录->成员账号

        @SuppressWarnings("unused")
        private String msgtype;//消息类型

        @SuppressWarnings("unused")
        private String agentid;//应用管理->AgentId

        @SuppressWarnings("unused")
        private Object markdown; //消息内容，实际为map类型

        public WeChatSendDataFormat(String touser, String msgtype, String agentid, Object markdown) {
            this.touser = touser;
            this.msgtype = msgtype;
            this.agentid = agentid;
            this.markdown = markdown;
        }
    }

}
